package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.ConditionVO;
import com.itheima.sfbx.insurance.enums.ConditionEnum;
import com.itheima.sfbx.insurance.mapper.ConditionMapper;
import com.itheima.sfbx.insurance.pojo.CategoryCondition;
import com.itheima.sfbx.insurance.pojo.Condition;
import com.itheima.sfbx.insurance.pojo.InsuranceCondition;
import com.itheima.sfbx.insurance.service.ICategoryConditionService;
import com.itheima.sfbx.insurance.service.IConditionService;
import com.itheima.sfbx.insurance.service.IInsuranceConditionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description：筛选项服务实现类
 */
@Slf4j
@Service
public class ConditionServiceImpl extends ServiceImpl<ConditionMapper, Condition> implements IConditionService {


    public LambdaQueryWrapper<Condition> lpw(ConditionVO conditionVO) {
        LambdaQueryWrapper<Condition> lambdaQueryWrapper = Wrappers.<Condition>lambdaQuery()
                .eq(StrUtil.isNotEmpty(conditionVO.getConditionKey()), Condition::getConditionKey, conditionVO.getConditionKey())
                .like(StrUtil.isNotEmpty(conditionVO.getConditionKeyName()), Condition::getConditionKeyName, conditionVO.getConditionKeyName())
                .eq(StrUtil.isNotEmpty(conditionVO.getDataState()), Condition::getDataState, conditionVO.getDataState());
        return lambdaQueryWrapper;
    }

    @Override
    public Page<ConditionVO> findPage(ConditionVO conditionVO, int pageNum, int pageSize) {
        Page<Condition> page = this.page(new Page<>(pageNum, pageSize), lpw(conditionVO));
        return BeanConv.toPage(page, ConditionVO.class);
    }

    @Override
    public ConditionVO findById(String conditionId) {
        Condition byId = this.getById(conditionId);
        if (byId == null) {
            log.error("筛选项单条查询：{}", conditionId);
            throw new ProjectException(ConditionEnum.FIND_ONE_FAIL);
        }
        return BeanConv.toBean(byId, ConditionVO.class);
    }


    @Override
    @Transactional
    public ConditionVO save(ConditionVO conditionVO) {
        //判断key是否存在
        Integer count = lambdaQuery().eq(Condition::getConditionKey, conditionVO.getConditionKey())
                .count();
        if (count > 0) {
            log.error("key已存在");
            throw new ProjectException(ConditionEnum.SAVE_FAIL);
        }
        //转化对象
        Condition bean = BeanConv.toBean(conditionVO, Condition.class);
        this.save(bean);
        return BeanConv.toBean(bean, ConditionVO.class);
    }

    @Autowired
    private IInsuranceConditionService insuranceConditionService;
    @Autowired
    private ICategoryConditionService categoryConditionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(ConditionVO conditionVO) {
        //判断key是否存在
        Integer count = this.lambdaQuery()
                .eq(Condition::getConditionKey, conditionVO.getConditionKey())
                .ne(Condition::getId, conditionVO.getId())//去掉自身
                .count();
        if (count > 0) {
            log.error("key已存在,{}", conditionVO.getConditionKey());
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }
        //判断是否有别的关联关系
        Integer count1 = insuranceConditionService.lambdaQuery()
                .eq(InsuranceCondition::getConditionKey, conditionVO.getConditionKey())
                .count();
        Integer count2 = categoryConditionService.lambdaQuery()
                .eq(CategoryCondition::getConditionKey, conditionVO.getConditionKey())
                .count();
        if (count1 > 0 || count2 > 0) {
            log.error("存在关联关系,{}", conditionVO.getConditionKey());
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }
        //执行修改
        boolean b = updateById(BeanConv.toBean(conditionVO, Condition.class));
        if (!b) {
            log.error("执行修改失败,{}", conditionVO.getConditionKey());
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }
        return b;
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        List<String> ids = Arrays.asList(checkedIds);
        List<Condition> olds = listByIds(ids);
        if (CollUtil.isEmpty(olds)) {
            return true;
        }
        Set<String> keySet = olds.stream().map(Condition::getConditionKey).collect(Collectors.toSet());
        //判断是否有别的关联关系
        Integer count1 = insuranceConditionService.lambdaQuery()
                .in(InsuranceCondition::getConditionKey, keySet)
                .eq(InsuranceCondition::getDataState, SuperConstant.DATA_STATE_0)
                .count();
        Integer count2 = categoryConditionService.lambdaQuery()
                .in(CategoryCondition::getConditionKey, keySet)
                .eq(CategoryCondition::getDataState, SuperConstant.DATA_STATE_0)
                .count();
        if (count1 > 0 || count2 > 0) {
            log.error("存在关联关系,{}", keySet);
            throw new ProjectException(ConditionEnum.DEL_FAIL);
        }
        return removeByIds(ids);
    }

    @Override
    public List<ConditionVO> findList(ConditionVO conditionVO) {
        List<Condition> list = this.list(lpw(conditionVO));
        return BeanConv.toBeanList(list, ConditionVO.class);
    }

    @Override
    public List<ConditionVO> findInConditionKeys(List<String> conditionKeys) {
        List<Condition> collect = conditionKeys.stream().map(x -> this.lambdaQuery().eq(Condition::getConditionKey, x).one()).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
            log.error("根据条件key查询筛选项为空,{}", conditionKeys);
            throw new ProjectException(ConditionEnum.LIST_FAIL);
        }
        return BeanConv.toBeanList(collect, ConditionVO.class);
    }
}
